package com.qst.rongxiaotong.aspect;



import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Ww
 * @version v1.0
 * @className AutoFillspect
 * @description
 * @date 2024/9/17 20:04
 **/
@Aspect
@Component
@Slf4j
public class AutoFillAspect {


    @Pointcut ("execution(* com.qst.rongxiaotong.mapper.*.*(..))&& @annotation(com.qst.rongxiaotong.aspect.AutoFill)")
    public  void  autoFillPointCut(){

    }

    @Before ("autoFillPointCut()")
    public  void autoFill(JoinPoint joinPoint){
        log.info("开始进行前置通知！");
        // 获取操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();


        Object[] args = joinPoint.getArgs(); //获得了方法所有的参数
        if(args == null || args.length==0 ){ //没有参数
            return;
        }
        Object entity = args[0];//现在约定实体放在第1个位置,传入实体可能不同所以用Object

        LocalDateTime now = LocalDateTime.now();
        if(operationType == OperationType.INSERT){
            //为4个公共字段赋值
            setField(entity, AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class,now);
            setField(entity,AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class,now);

        }else if(operationType == OperationType.UPDATE){
            setField(entity,AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class,now);
        }
    }


    private void setField(Object entity,String setName,Class<?> valueclass,Object value){
        //为4个公共字段赋值
        try {
            // 获取并调用 setCreateTime
            Method setCreateTime = entity.getClass().getDeclaredMethod(setName,valueclass);
            setCreateTime.invoke(entity, value);
        } catch (NoSuchMethodException e) {
            log.warn("setCreateTime method not found in " + entity.getClass().getName());
        } catch (Exception e) {
            e.printStackTrace(); // 处理其他可能的异常
        }
    }


}
